package com.study.map.util;

import com.alibaba.fastjson.JSON;
import com.study.map.config.GaodeMapConfig;
import com.study.map.exception.MapServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 地图HTTP工具类
 *
 * @author study
 * @date 2025-08-31
 */
@Slf4j
@Component
public class MapHttpUtil {

    @Autowired
    private GaodeMapConfig gaodeMapConfig;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 发送GET请求
     *
     * @param url 请求URL
     * @param params 请求参数
     * @return 响应结果
     * @throws MapServiceException 地图服务异常
     */
    public <T> T doGet(String url, Map<String, Object> params, Class<T> responseType) throws MapServiceException {

        try {
            // 构建带参数的URL
            UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
            if (params != null) {
                params.forEach((key, value) -> {
                    if (value != null) {
                        builder.queryParam(key, value);
                    }
                });
            }

            // 添加API Key
            builder.queryParam("key", gaodeMapConfig.getApiKey());

            URI uri = builder.build().encode().toUri();
            log.debug("发送GET请求: {}", uri.toString());

//            HttpHeaders headers = new HttpHeaders();
//            headers.setContentType(MediaType.APPLICATION_JSON);
//
//            HttpEntity<String> entity = new HttpEntity<String>(headers);
//
//            ResponseEntity<String> response = restTemplate.exchange(
//                    uri,
//                    HttpMethod.GET,
//                    entity,
//                    responseType
//            );
//
//            log.debug("GET请求响应: {}", response.getBody());
//            return response.getBody();
            T response = restTemplate.getForObject(uri, responseType);
            log.debug("GET请求响应: {}", response);
            return response;
        } catch (RestClientException e) {
            log.error("发送GET请求异常", e);
            throw new MapServiceException("请求高德地图API失败", e);
        }
    }

    /**
     * 发送POST请求
     *
     * @param url 请求URL
     * @param params 请求参数
     * @return 响应结果
     * @throws MapServiceException 地图服务异常
     */
    public String doPost(String url, Map<String, Object> params) throws MapServiceException {

        try {
            // 添加API Key到参数中
            if (params != null) {
                params.put("key", gaodeMapConfig.getApiKey());
            }

            log.debug("发送POST请求: {}, 参数: {}", url, JSON.toJSONString(params));

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            MultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap<>();
            if (params != null) {
                params.forEach((key, value) -> {
                    if (value != null) {
                        multiValueMap.add(key, value);
                    }
                });
            }

            HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(multiValueMap, headers);

            ResponseEntity<String> response = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    entity,
                    String.class
            );

            log.debug("POST请求响应: {}", response.getBody());
            return response.getBody();
        } catch (RestClientException e) {
            log.error("发送POST请求异常", e);
            throw new MapServiceException("请求高德地图API失败", e);
        }
    }

}